package com.tanhua.manager.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.vo.ErrorResult;
import com.tanhua.manager.constant.CacheKey;
import com.tanhua.manager.domain.Admin;
import com.tanhua.manager.exception.BusinessException;
import com.tanhua.manager.interceptor.AdminHolder;
import com.tanhua.manager.mapper.AdminMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 阿鹏
 * @date 2021/2/18 22:08
 */
@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${tanhua.secret}")
    private String secret;

    public void cacheCode(String code, String uuid) {
        redisTemplate.opsForValue().set(CacheKey.CODE_PREFIX + uuid, code, Duration.ofHours(5));
    }

    /**
     *
     * @param username 用户名
     * @param password 密码
     * @param verificationCode 验证码
     * @param uuid uuid
     * @return token
     */
    public ResponseEntity adminLogin(String username, String password, String verificationCode, String uuid) {
        String code = redisTemplate.opsForValue().get(CacheKey.CODE_PREFIX + uuid);
        if (code == null || !StringUtils.equals(verificationCode, code)) {
            throw new BusinessException("验证码错误");
        }
        // 验证码校验成功,删除验证码
        redisTemplate.delete(CacheKey.CODE_PREFIX + uuid);

        // 校验用户名和密码
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Admin admin = this.baseMapper.selectOne(wrapper);

        if (admin == null) {
            throw new BusinessException("用户不存在");
        }

        if (StringUtils.isBlank(password) || !StringUtils.equals(SecureUtil.md5(password), admin.getPassword())) {
            throw new BusinessException("密码错误");
        }

        // 生成token,缓存到redis中
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", admin.getId());
        claims.put("username", admin.getUsername());
        String token = Jwts.builder().setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();

        redisTemplate.opsForValue().set(CacheKey.TOKEN_PREFIX + token, JSON.toJSONString(admin), Duration.ofHours(1));

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity getAdminInfo() {
        Admin admin = AdminHolder.getAdmin();

        Map<String, Object> result = new HashMap<>();
        result.put("id", admin.getId().toString());
        result.put("username", admin.getUsername());
        result.put("avatar", admin.getAvatar());
        return ResponseEntity.ok(result);
    }

    public ResponseEntity logout() {
        String token = AdminHolder.getToken();
        redisTemplate.delete(CacheKey.TOKEN_PREFIX + token);
        return ResponseEntity.ok(null);
    }
}
